<?php
/**
 * 【停止执行】
 * 维护article索引表
 * Created by PhpStorm.
 * User: zhangshuai
 * Date: 2019/3/22
 * Time: 14:50
 */

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\common\service\ElasticSearch;
use think\Exception;

class ElSearchArticles extends Command {
    // 0 1 * * 1 /usr/local/qqwebsrv/php/bin/php /data/phpAdmin/think setElSearchArticles
    protected function configure() {
        // 设置命令名称 以及 命令说明
        $this->setName('setElSearchArticles')->setDescription('维护文章索引');
    }

    // execute()函数是要执行的命令，这里可以直接写需要完成的任务或者调用类中任务方法。
    protected function execute(Input $input, Output $output) {
        #$this->setElSearchArticles($input, $output);
    }

    /**
     * 将article表数据插入ES索引数据
     *
     * @param Input $input
     * @param Output $output
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function setElSearchArticles(Input $input, Output $output) {
        $start_time = get_millisecond();
        $output->writeln(date('Y-m-d H:i:s', time()) . " setElSearchArticles Command : === start");

        $elSearch = new ElasticSearch();

        //获取全网所有文章
        //$article_list = Db::table('article')->field('aid,title')->select();
        $offset = 0;
        do {
            //全量
            //$article_list = Db::table('article')->field('aid,title')->order('aid','asc')->limit($offset,500)->select();
            //昨天
            $article_list = Db::table('article')->where('t_time', '>', $start_time - 86400000)->field('aid,title')->order('aid', 'asc')->limit($offset, 500)->select();
            $output->writeln(json_encode($article_list));

            foreach ($article_list as $article) {
                $params = [
                    'index' => 'article',
                    'type' => 'article_type',
                    'id' => $article['aid'],
                    'body' => [
                        'title' => $article['title']
                    ]
                ];
                $elSearch->postSinDoc($params);

                $output->writeln(date('Y-m-d H:i:s', time()) . " setElSearchArticles Command : ===" . json_encode($params));
            }
            $offset = $offset + 500;
            sleep(1);

        } while ($article_list);

        $end_time = get_millisecond();
        $output->writeln(date('Y-m-d H:i:s', time()) . " setElSearchArticles Command : === end exec time " . ($end_time - $start_time) . 'ms');
    }
}